<template>
  <div>
    <el-upload
      :action="uploadUrl"
      :before-upload="beforeupload"
      :data="params"
      :headers="headers"
      :limit="1"
      :name="name"
      :on-remove="handleRemove"
      :on-success="handleAvatarSuccess"
      :show-file-list="false"
      class="avatar-uploader"
    >
      <template v-if="fellUrl">
        <video v-if="isVideo" :src="fellUrl" class="video" controls>
          <source :src="fellUrl" type="video/mp4">
        </video>
        <img v-else :src="fellUrl" alt="" class="avatar">
      </template>

      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <i v-if="fellUrl" class="el-icon-delete avatar-uploader-icon" @click.stop="handleRemove" />
    </el-upload>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'Index',

  props: ['value', 'name'],
  data() {
    return {
      params: {},
      labelWidth: '120px',
      isVideo: false,
      uploadUrl: window.global.baseURL + '/admin/upload',
      headers: {
        'Authorization': getToken()
      },
      fellUrl: this.value
    }
  },
  watch: {
    value(val) {
      this.fellUrl = Array.isArray(val) ? val[0] : val
      // 判断是否是视频类型
      this.isVideo = this.isVideoLink(val)
    }
  },
  methods: {
    isVideoLink(url) {
      const videoExtensions = /\.(mp4|m4v|webm|mov|avi|wmv)$/i
      return videoExtensions.test(url)
    },
    handleRemove(file, fileList) {
      this.fellUrl = ''
      this.$emit('input', '')
    },
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.fellUrl = res.data
        this.$emit('input', res.data)
      } else {
        this.$message.error(res.msg)
      }
    },
    beforeupload(file) {
      const isLt2M = file.size / 1024 / 1024 < 50
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 50MB!')
      }
      return isLt2M
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 180px !important;
  height: 180px;
  line-height: 180px;
  text-align: center;
}

.avatar {
  z-index: 1;
  width: 180px !important;
  height: 180px !important;
  display: block !important;
  border-radius: 16px;
}

.video {
  z-index: 1;
  width: 180px !important;
  height: 180px !important;
  display: block !important;
  border-radius: 16px;
}

.el-icon-delete {
  position: absolute;
  z-index: 10;
  left: 0;
  top: 0;
  color: #fff;

  &:hover {
    color: #409EFF;
  }
}

.avatar-uploader-icon {
  border: 1px solid #ccc;
  border-radius: 16px;
}
</style>
